package cn.edu.baiyunu.myapplication.data.repository

import cn.edu.baiyunu.myapplication.data.dao.SettingsDao
import cn.edu.baiyunu.myapplication.data.model.Settings
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import javax.inject.Inject
import javax.inject.Singleton

/**
 * SettingsRepository接口的实现类
 */
@Singleton
class SettingsRepositoryImpl @Inject constructor(
    private val settingsDao: SettingsDao
) : SettingsRepository {
    
    override fun getSettings(): Flow<Settings?> {
        return settingsDao.getSettings()
    }
    
    override suspend fun updateUsername(username: String) {
        val currentSettings = getSettings().first() ?: Settings()
        settingsDao.updateSettings(currentSettings.copy(username = username))
    }
    
    override suspend fun updateSavingsGoal(amount: Double) {
        val currentSettings = getSettings().first() ?: Settings()
        settingsDao.updateSettings(currentSettings.copy(savingsGoal = amount))
    }
    
    override suspend fun updateThemeMode(mode: Int) {
        val currentSettings = getSettings().first() ?: Settings()
        settingsDao.updateSettings(currentSettings.copy(themeMode = mode))
    }
    
    override suspend fun updateCurrencyCode(code: String) {
        val currentSettings = getSettings().first() ?: Settings()
        settingsDao.updateSettings(currentSettings.copy(currencyCode = code))
    }
    
    override suspend fun initDefaultSettings() {
        // 检查是否已有设置
        val settings = getSettings().first()
        if (settings != null) {
            return // 已有设置，不需要初始化
        }
        
        // 创建并插入默认设置
        val defaultSettings = Settings(
            username = "用户",
            savingsGoal = 0.0,
            themeMode = 0, // 跟随系统
            currencyCode = "CNY"
        )
        settingsDao.insertSettings(defaultSettings)
    }
} 